var carousel = document.querySelector(".carousel"),
  caro_img = document.querySelector(".caro_img"),
  left_arr = document.querySelector(".left_arr"),
  right_arr = document.querySelector(".right_arr"),
  clone_first = caro_img.firstElementChild.cloneNode(true),
  clone_last = caro_img.lastElementChild.cloneNode(true),
  dot = document.querySelector(".dot"),
  dot_lis = dot.getElementsByTagName("li"),
  now_num = 1,
  flag = true,
  timer = null;

// 生成小圆点
for (var i = 0; i < caro_img.childElementCount; i++) {
  dot.appendChild(document.createElement("li"));
}
dot.firstElementChild.classList.add("active");

// 将克隆的图片放到对应位置
caro_img.appendChild(clone_first);
caro_img.insertBefore(clone_last, caro_img.firstElementChild);
caro_img.style.transform = `translateX(-100%)`;

// 自动播放
auto_run();

// 左箭头
left_arr.addEventListener("click", function () {
  if (flag) {
    if (--now_num == 0) {
      run();
      now_num = caro_img.childElementCount - 2;
      end_run()
    } else {
      run();
    }
    dot_active();
    flag = false;
  }
})

// 右箭头
right_arr.addEventListener("click", function () {
  if(flag){
    if (++now_num == caro_img.childElementCount - 1) {
      run();
      now_num = 1;
      end_run();
    } else {
      run();
    }
    dot_active();
    flag = false;
  }
})

// 开启点击事件
caro_img.addEventListener("transitionend", function () {
  flag = true;
})

// 鼠标进入时清除定时器
carousel.addEventListener("mouseenter",function(){
  clearInterval(timer);
})

// 鼠标移出时重新开启定时器
carousel.addEventListener("mouseleave",function(){
  auto_run();
})

// 点击圆点跳转到对应图片
Array.from(dot_lis).forEach(function(li_obj,index){
  li_obj.addEventListener("click",function(){
    now_num = index + 1;
    caro_img.style.transform = `translateX(-${now_num}00%)`;
    dot_active();
  })
})

// 定义自动播放
function auto_run(){
  timer = setInterval(() => {
    if(flag){
      if (++now_num == caro_img.childElementCount - 1) {
        run();
        now_num = 1;
        end_run();
      } else {
        run();
      }
      dot_active();
      flag = false;
    }
  }, 2000);
}

// 正常动画
function run() {
  caro_img.style.transition = "all 0.5s";
  caro_img.style.transform = `translateX(-${now_num}00%)`;
}

// 尽头动画
function end_run() {
  caro_img.addEventListener("transitionend", function () {
    caro_img.style.transition = "none";
    caro_img.style.transform = `translateX(-${now_num}00%)`;
  }, {
    once: true
  })
}

// 圆点选中
function dot_active(){
  [...dot_lis].forEach(function(li_obj,index){
    if(index == now_num-1){
      li_obj.classList.add("active");
    }else {
      li_obj.classList.remove("active");
    }
  })
}